﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Kingdee.BOS.WebApi.ServicesStub;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RK.Model;
using RK.Model.BPW;
using Kingdee.BOS.ServiceHelper;

namespace RK.ExtendWebApi.BPW
{
    public class PurchaseConfirmation : AbstractWebApiBusinessService
    {
        public PurchaseConfirmation(KDServiceContext AppContext) : base(AppContext)
        {

        }
        public object Confirmation(string CFxml)
        {
            var ctx = KDContext.Session.AppContext;
            if (ctx == null)
            {
                throw new Exception("ctx = null,会话超时，需重新登录!");
            }
            XmlModel xmlModel = new XmlModel();
            xmlModel.Model = new Model.BPW.Model();
            xmlModel.Model.FEntity = new List<FEntityItem>();

            //把XML字符串载入XML文档模式
            XmlDocument xmlDocument = new XmlDocument();
            try
            {
                xmlDocument.LoadXml(CFxml);
            }
            catch (Exception ex)
            {
                ErrResult errResult = new ErrResult()
                {
                    Result = new Model.BPW.Result()
                    {
                        ResponseStatus = new Model.BPW.ResponseStatus()
                        {
                            ErrorCode = 500,
                            IsSuccess = false,
                            MsgCode = 4,
                            Errors = new List<Model.BPW.ErrorsItem>()
                            {
                                new Model.BPW.ErrorsItem()
                                {
                                    DIndex=0,
                                    FieldName="Exception",
                                    Message=ex.Message
                                }
                            }
                        }
                    }
                };
                return JsonConvert.SerializeObject(errResult);
            }
            string FPURFID = "0";
            //采购确认单，表头
            XmlNodeList xmlHeader = xmlDocument.SelectNodes("/ORDERRESPONSE/ORDERRESPONSE_HEADER");
            if (xmlHeader != null)
            {
                foreach (XmlNode xmlNode in xmlHeader)
                {
                    foreach (XmlNode xmlNode2 in xmlNode.ChildNodes)
                    {
                        if (xmlNode2.Name == "ORDERRESPONSE_INFO")
                        {
                            foreach (XmlNode xmlNode3 in xmlNode2.ChildNodes)
                            {
                                if (xmlNode3.Name == "ORDER_ID")
                                {
                                    xmlModel.Model.FORDER_ID = xmlNode3.InnerText;
                                    string fidSql = string.Format($"/*dialect*/ select FID from T_PUR_POORDER where FBILLNO='{xmlNode3.InnerText}'");
                                    DataSet fidDs = DBServiceHelper.ExecuteDataSet(ctx, fidSql);
                                    if (fidDs.Tables[0].Rows.Count > 0)
                                    {
                                        FPURFID = fidDs.Tables[0].Rows[0][0].ToString();
                                    }
                                    if (FPURFID.IsNullOrEmptyOrWhiteSpace())
                                    {
                                        ErrResult errResult = new ErrResult()
                                        {
                                            Result = new Model.BPW.Result()
                                            {
                                                ResponseStatus = new Model.BPW.ResponseStatus()
                                                {
                                                    ErrorCode = 500,
                                                    IsSuccess = false,
                                                    MsgCode = 4,
                                                    Errors = new List<Model.BPW.ErrorsItem>()
                                                        {
                                                            new Model.BPW.ErrorsItem()
                                                            {
                                                                DIndex = 0,
                                                                FieldName = "对应FID不存在！",
                                                                Message ="ORDER_ID:"+xmlNode3.InnerText+ "对应的金蝶采购订单FID不存在！"
                                                            }
                                                        }
                                                }
                                            }
                                        };
                                        return JsonConvert.SerializeObject(errResult);
                                    }
                                    xmlModel.Model.FPURFID = FPURFID;
                                }
                                if (xmlNode3.Name == "SUPPLIER_ORDER_ID")
                                {
                                    xmlModel.Model.FSUPPLIER_ORDER_ID = xmlNode3.InnerText;
                                }
                                if (xmlNode3.Name == "ORDER_PARTIES")
                                {
                                    foreach (XmlNode xmlNode4 in xmlNode3.ChildNodes)
                                    {
                                        if (xmlNode4.Name == "BUYER_PARTY")
                                        {
                                            foreach (XmlNode xmlNode1 in xmlNode4.ChildNodes)
                                            {
                                                if (xmlNode1.Name == "PARTY")
                                                {
                                                    foreach (XmlNode xmlNode6 in xmlNode1.ChildNodes)
                                                    {
                                                        if (xmlNode6.Name == "PARTY_ID")
                                                        {
                                                            xmlModel.Model.FPARTY_ID = xmlNode6.InnerText;
                                                        }
                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                                if (xmlNode3.Name == "ORDER_DATE")
                                {
                                    xmlModel.Model.FORDER_DATE = Convert.ToDateTime(xmlNode3.InnerText);
                                }
                                if (xmlNode3.Name == "ORDERRESPONSE_DATE")
                                {
                                    xmlModel.Model.FORDERRESPONSE_DATE = Convert.ToDateTime(xmlNode3.InnerText);
                                }
                                if (xmlNode3.Name == "DELIVERY_DATE")
                                {
                                    foreach (XmlNode xmlNode1in in xmlNode3.ChildNodes)
                                    {
                                        if (xmlNode1in.Name == "DELIVERY_START_DATE")
                                        {
                                            xmlModel.Model.FDELVIVERY_START_DATE = Convert.ToDateTime(xmlNode1in.InnerText);
                                        }
                                        if (xmlNode1in.Name == "DELIVERY_END_DATE")
                                        {
                                            xmlModel.Model.FDELIVERY_END_DATE = Convert.ToDateTime(xmlNode1in.InnerText);
                                        }
                                    }
                                }
                                if (xmlNode3.Name == "PRICE_CURRENCY")
                                {
                                    xmlModel.Model.FPRICE_CURRENCY = xmlNode3.InnerText;
                                }
                            }
                        }
                    }
                }
            }
            //表体
            XmlNodeList xmlEntity = xmlDocument.SelectNodes("/ORDERRESPONSE/ORDERRESPONSE_ITEM_LIST/ORDERRESPONSE_ITEM");
            if (xmlEntity != null)
            {
                foreach (XmlNode xmlNode2 in xmlEntity)
                {
                    if (xmlNode2.Name == "ORDERRESPONSE_ITEM")
                    {
                        var entityRow = new FEntityItem();
                        entityRow.F_XRIS_Date = DateTime.UtcNow;
                        foreach (XmlNode xmlNode in xmlNode2.ChildNodes)
                        {
                            if (xmlNode.Name == "LINE_ITEM_ID")
                            {
                                entityRow.FLINE_ITEM_ID = xmlNode.InnerText;
                            }
                            if (xmlNode.Name == "ARTICLE_ID")
                            {
                                foreach (XmlNode xmlNode4 in xmlNode.ChildNodes)
                                {
                                    if (xmlNode4.Name == "SUPPLIER_AID")
                                    {
                                        string materialNumber = string.Empty;//GetMaterial(xmlNode4.InnerText, ctx);
                                        string F_BPW_INEXNUMBER = GetRemotZero(xmlNode4.InnerText);
                                        string materSql = string.Format($"/*dialect*/ select FNUMBER from T_BD_MATERIAL where CASE WHEN SUBSTRING(F_BPW_INEXNUMBER,1,1)='0' THEN SUBSTRING(F_BPW_INEXNUMBER,2,LEN(F_BPW_INEXNUMBER)-1) ELSE F_BPW_INEXNUMBER END ='{F_BPW_INEXNUMBER}'");
                                        DataSet materDs = DBServiceHelper.ExecuteDataSet(ctx, materSql);
                                        if (materDs.Tables[0].Rows.Count > 0)
                                        {
                                            materialNumber = materDs.Tables[0].Rows[0][0].ToString();
                                        }
                                        if (materialNumber.IsNullOrEmptyOrWhiteSpace())
                                        {
                                            ErrResult errResult = new ErrResult()
                                            {
                                                Result = new Model.BPW.Result()
                                                {
                                                    ResponseStatus = new Model.BPW.ResponseStatus()
                                                    {
                                                        ErrorCode = 500,
                                                        IsSuccess = false,
                                                        MsgCode = 4,
                                                        Errors = new List<Model.BPW.ErrorsItem>()
                                                        {
                                                            new Model.BPW.ErrorsItem()
                                                            {
                                                                DIndex = 0,
                                                                FieldName = "对应物料编码不存在！",
                                                                Message ="SUPPLIER_AID:"+xmlNode4.InnerText+ "对应的金蝶物料编码不存在！"
                                                            }
                                                        }
                                                    }
                                                }
                                            };
                                            return JsonConvert.SerializeObject(errResult);
                                        }
                                        entityRow.FSUPPLIER_AID = new FSUPPLIER_AID() { FNUMBER = materialNumber };
                                        string listSql = string.Format($@"/*dialect*/ 
                                        SELECT t0.FENTRYID, 
                                               t0.FQTY, 
                                               t2.FNUMBER, 
                                               t3.FTaxPrice, 
                                               t3.FAllAmount, 
                                               t4.FDeliveryEarlyDate, 
                                               t5.FPREARRIVALDATE, 
                                               t0.FSEQ,
                                               t3.FPRICE,t3.FAMOUNT
                                        FROM T_PUR_POORDERENTRY t0
                                             JOIN T_BD_MATERIAL t1 ON t1.FMATERIALID = t0.FMATERIALID
                                             JOIN T_BD_UNIT t2 ON t2.FUNITID = t0.FUNITID
                                             JOIN T_PUR_POORDERENTRY_F t3 ON t3.FENTRYID = t0.FENTRYID
                                             JOIN T_PUR_POORDERENTRY_D t4 ON t4.FENTRYID = t0.FENTRYID
                                             JOIN t_PUR_POENTRYDELIPLAN t5 ON t5.FENTRYID = t0.FENTRYID
                                        WHERE t0.FID = {FPURFID}
                                              AND t1.FNUMBER = '{materialNumber}'");
                                        DataSet listDs = DBServiceHelper.ExecuteDataSet(ctx, listSql);
                                        if (listDs.Tables[0].Rows.Count > 0)
                                        {
                                            var list = listDs.Tables[0].Rows[0];
                                            entityRow.FPURENTRYID = list[0].ToString();
                                            entityRow.FQty = Convert.ToDecimal(list[1]);
                                            entityRow.FUNIT = new FUNIT() { FNUMBER = list[2].ToString() };
                                            entityRow.F_XRIS_Price = Convert.ToDecimal(list[3]);
                                            entityRow.F_XRIS_Amount = Convert.ToDecimal(list[4]);
                                            entityRow.FDeliveryEarlyDate = Convert.ToDateTime(list[5]);
                                            entityRow.FPREARRIVALDATE = Convert.ToDateTime(list[6]);
                                            entityRow.F_XRIS_Seq = Convert.ToInt32(list[7]);
                                            entityRow.F_XRIS_Price_qtr = Convert.ToDecimal(list[8]);
                                            entityRow.F_XRIS_Amount_83g = Convert.ToDecimal(list[9]);
                                        }
                                    }
                                    if (xmlNode4.Name == "BUYER_AID")
                                    {
                                        entityRow.FBUYER_AID = xmlNode4.InnerText;
                                    }
                                    if (xmlNode4.Name == "DESCRIPTION_SHORT")
                                    {
                                        entityRow.FDESCRIPTION_SHORT = xmlNode4.InnerText;
                                    }
                                }
                            }
                            if (xmlNode.Name == "QUANTITY")
                            {
                                entityRow.FQUANTITY = Convert.ToDecimal(xmlNode.InnerText);
                            }
                            if (xmlNode.Name == "ORDER_UNIT")
                            {
                                entityRow.FORDER_UNIT = xmlNode.InnerText;
                            }
                            if (xmlNode.Name == "ARTICLE_PRICE")
                            {
                                foreach (XmlNode xmlNode5 in xmlNode.ChildNodes)
                                {
                                    if (xmlNode5.Name == "PRICE_AMOUNT")
                                    {
                                        entityRow.FPRICE_AMOUNT = Convert.ToDecimal(xmlNode5.InnerText);
                                    }
                                    if (xmlNode5.Name == "PRICE_LINE_AMOUNT")
                                    {
                                        entityRow.FPRICE_LINE_AMOUNT = Convert.ToDecimal(xmlNode5.InnerText);
                                    }
                                }
                            }
                            if (xmlNode.Name == "DELIVERY_DATE")
                            {
                                foreach (XmlNode xmlNode1 in xmlNode.ChildNodes)
                                {
                                    if (xmlNode1.Name == "DELIVERY_START_DATE")
                                    {
                                        entityRow.F_BPW_CREATEDATE = Convert.ToDateTime(xmlNode1.InnerText);
                                    }
                                }
                            }
                        }
                        xmlModel.Model.FEntity.Add(entityRow);
                    }
                }
            }
            //SUM
            XmlNodeList xmlSum = xmlDocument.SelectNodes("/ORDERRESPONSE/ORDERRESPONSE_SUMMARY");
            if (xmlSum != null)
            {
                foreach (XmlNode xmlNode2 in xmlSum)
                {
                    foreach (XmlNode xmlNode3 in xmlNode2)
                    {
                        if (xmlNode3.Name == "TOTAL_AMOUNT")
                        {
                            xmlModel.Model.FTOTAL_ITEM_NUM = Convert.ToDecimal(xmlNode3.InnerText);
                        }
                    }
                }
            }
            var jsonStr = JsonConvert.SerializeObject(xmlModel);
            var saveResult = JsonConvert.SerializeObject(WebApiServiceCall.Save(ctx, "XRIS_PurchaseConfirmation", jsonStr));
            JObject result = JObject.Parse(saveResult);
            var isSuccess = result["Result"]["ResponseStatus"]["IsSuccess"].Value<bool>();
            if (!isSuccess)
            {
                var message = result["Result"]["ResponseStatus"]["Errors"][0]["Message"].Value<string>();
                ErrResult errResult = new ErrResult()
                {
                    Result = new Model.BPW.Result()
                    {
                        ResponseStatus = new Model.BPW.ResponseStatus()
                        {
                            ErrorCode = 500,
                            IsSuccess = false,
                            MsgCode = 4,
                            Errors = new List<Model.BPW.ErrorsItem>()
                            {
                                new Model.BPW.ErrorsItem()
                                {
                                    DIndex=0,
                                    FieldName="WebApiServiceCall.Save(ctx, \"XRIS_PurchaseConfirmation\", jsonStr",
                                    Message=message
                                }
                            }
                        }
                    }
                };
                return JsonConvert.SerializeObject(errResult);
            }
            return result;
        }
        /// <summary>
        /// 判断字符串第一个字符是否为0，如为0则取第二位后的所有字符组成新字串
        /// </summary>
        /// <param name="innerText"></param>
        /// <returns></returns>
        private string GetRemotZero(string innerText)
        {
            string resultStr = string.Empty;
            var firstStr = innerText.Substring(0, 1);
            if (firstStr == "0")
            {
                resultStr = innerText.Substring(1);
            }
            else
            {
                resultStr = innerText;
            }
            return resultStr;
        }

        private string GetMaterial(string innerText, Kingdee.BOS.Context ctx)
        {
            string number = string.Empty;
            var param = new
            {
                FormId = "BD_MATERIAL",
                FieldKeys = "fnumber",
                FilterString = $"F_BPW_INEXNUMBER='{innerText}'"
            };
            var result = WebApiServiceCall.ExecuteBillQuery(ctx, JsonConvert.SerializeObject(param));
            number = result[0][0].ToString();
            return number;
        }

        private List<object> GetPurEntyId(string fPURFID, string innerText, Kingdee.BOS.Context ctx)
        {
            List<object> list = new List<object>();
            var param = new
            {
                FormId = "PUR_PurchaseOrder",
                FieldKeys = "FPOOrderEntry_FEntryId,fqty,FUnitId.fnumber,FTaxPrice,FAllAmount,FDeliveryEarlyDate,FPREARRIVALDATE,FPOOrderEntry_Fseq",
                FilterString = $"fid={fPURFID} and fmaterialid.Fnumber='{innerText}'"
            };
            var result = WebApiServiceCall.ExecuteBillQuery(ctx, JsonConvert.SerializeObject(param));
            foreach (var item in result)
            {
                list.Add(item);
            }
            return list;
        }

        private string GetPurFid(Kingdee.BOS.Context ctx, string innerText)
        {
            string fid = string.Empty;
            var param = new
            {
                FormId = "PUR_PurchaseOrder",
                FieldKeys = "FID",
                FilterString = "Fbillno=" + innerText
            };
            var result = WebApiServiceCall.ExecuteBillQuery(ctx, JsonConvert.SerializeObject(param));
            foreach (var item in result)
            {
                fid = item[0].ToString();
            }
            return fid;
        }

        /// <summary>
        /// xml转换成json
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private string ToJson(string xml)
        {
            var json = new JObject(new JProperty(XDocument.Parse(xml).Root.Name.LocalName, new JObject(XDocument.Parse(xml).Root.Descendants().Select(n =>
            {
                if (!n.HasElements) { return new JProperty(n.Name.LocalName, n.Value); }
                return new JProperty(n.Name.LocalName, new JObject(n.Descendants().Select(x => new JProperty(x.Name.LocalName, x.Value))));
            }))));
            return json.ToString();
        }
    }
}
